# -*- coding: utf-8 -*-

# 绘制每个行政区的NDVI变化图，每幅图有生长期平均值和全年平均值

import os
import json
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import make_interp_spline
from matplotlib import font_manager  # 导入字体管理模块
from liner_analysis import analyze

my_font = font_manager.FontProperties(fname="C:/WINDOWS/Fonts/STSONG.TTF")

plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

label_font = {'family': 'serif',
              'color': 'black',
              'weight': 'normal',
              'size': 16,
              }

legend_font = {'family': "STSONG",
               # 'color': 'black',
               'weight': 'normal',
               'size': 15,
               }

with open("avgRecord.json") as f:
    data = json.load(f)
    d1 = data['QuNDVI_Excel']


def draw(title, fig, params, py):
    x = ['2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013',
         '2014', '2015', '2016', '2017', '2018', '2019', '2020']
    xx = np.arange(0, len(x), 1)
    xn = np.array(xx)
    x_smooth = np.linspace(xn.min(), xn.max(), 300)
    y = py
    y_year_avg = y['year_avg']
    y_growth_avg = y['growth_avg']

    y_predict_year_avg = analyze(y, "year_avg")[0] + xx * analyze(y, "year_avg")[1]
    y_predict_growth_avg = analyze(y, "growth_avg")[0] + xx * analyze(y, "year_avg")[1]
    annotation_year = "y_year = %fx + %f" % (analyze(y, "year_avg")[1], analyze(y, "year_avg")[0])
    annotation_growth = "y_growth = %fx + %f" % (analyze(y, "growth_avg")[1], analyze(y, "growth_avg")[0])
    y_year_avg_smooth = make_interp_spline(xn, y_year_avg)(x_smooth)
    y_growth_avg_smooth = make_interp_spline(xn, y_growth_avg)(x_smooth)
    plt__ = fig.add_subplot(params)
    # plt__.text(1, max(y_year_avg) , annotation_year,  fontdict=dict(fontsize=16, color='r',family='STSONG',))
    # plt__.text(1, max(y_year_avg)+ 2*sum(y_year_avg)/len(y_year_avg), annotation_growth)
    plt__.plot(x_smooth, y_year_avg_smooth, label="年平均变化趋势")
    plt__.plot(x_smooth, y_growth_avg_smooth, label="生长期（4-10月）变化趋势")

    plt__.plot(x, y_predict_year_avg, label="预测年平均变化趋势 \ny_year = %fx + %f"
                                            % (analyze(y, "year_avg")[1], analyze(y, "year_avg")[0]),
                                            linestyle="--")
    plt__.plot(x, y_predict_growth_avg, label="预测生长期（4-10月）变化趋势 \ny_growth = %fx + %f"
                                              % (analyze(y, "growth_avg")[1], analyze(y, "growth_avg")[0]),
                                            linestyle="--")

    plt__.set_title("%sNDVI变化趋势图" % title, fontproperties=my_font, fontsize=20, pad=20)

    plt__.set_xlabel("Year", fontdict=label_font)
    plt__.set_ylabel("NDVI", fontdict=label_font)
    # plt__.legend(loc=4, prop=legend_font,  bbox_to_anchor=(1.4, 0), borderaxespad=0)
    plt__.legend(loc=2, prop=legend_font, framealpha=0, shadow=False)
    plt__.grid(alpha=0.1, color='g', which="major")


def run(save_name, keys, fig, data):
    c = 621
    for i in keys:
        print(i)
        print(data[i])
        draw(title=i, fig=fig, params=c, py=data[i])
        c += 1
        t = ['2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012',
             '2013',
             '2014', '2015', '2016', '2017', '2018', '2019', '2020']
        plt.xticks(np.arange(0, len(t), 1), t, fontproperties='Times New Roman', size=14)
        plt.yticks(fontproperties='Times New Roman', size=14)
        plt.tight_layout(pad=8, w_pad=1.5, h_pad=8)
    plt.savefig(save_name)
    # plt.show()
    plt.clf()


if __name__ == '__main__':
    nx1 = "E:\\毕设数据\\pictures\\行政区_NDVI_1.pdf"
    nx2 = "E:\\毕设数据\\pictures\\行政区_NDVI_2.pdf"
    nu = "E:\\毕设数据\\pictures\\UsingTypeNDVI.pdf"
    nv = "E:\\毕设数据\\pictures\\VegetationTypeNDVI.pdf"

    key_x1 = list(d1)[:6]
    key_x2 = list(d1)[6:]
    key_u = list(data["UsingTypeNDVI_Excel"])
    key_v = list(data["VegetationTypeNDVI_Excel"])
    fig = plt.figure(figsize=(30, 60), dpi=160)
    # run(save_name=n1, fig=fig, keys=key1)
    # run(save_name=n2, fig=fig, keys=key2)
    run(save_name=nx1, keys=key_x1, fig=fig, data=data["QuNDVI_Excel"])
    run(save_name=nx2, keys=key_x2, fig=fig, data=data["QuNDVI_Excel"])
    run(save_name=nu, keys=key_u, fig=fig, data=data["UsingTypeNDVI_Excel"])
    run(save_name=nv, keys=key_v, fig=fig, data=data["VegetationTypeNDVI_Excel"])
